package ru.dc.object.commands;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * This command is sent by the client to the hub to find out the IP addresses of one or more
 * users. In the case of multiple users, $$ is used as a delimiter, as in $NickList and $OpList.
 * The IP address the hub reports should be the one at the remote end of the hub connection;
 * this address differ from the one reported in $ConnectToMe. DC++ will not request its own
 * IP address; hubs supporting the UserIP2 protocol extension should automatically send the
 * client its own IP.
 * </p>
 * <p>
 * <a href="http://www.teamfair.info/wiki/index.php?title=$UserIP">http://www.teamfair.info/wiki/index.php?title=$UserIP</a>
 * </p>
 * <pre>
 * User: deady
 * Date: 31.10.2010
 * Time: 13:14:47
 * </pre>
 */
public class UserIP extends Command {

    private Map<String, String> userAddresses = new HashMap<String, String>();

    @Override
    public String getActualCommandName() {
        return "$UserIP";
    }

    @Override
    public String generateCommand() {
        StringBuilder sb = new StringBuilder(getActualCommandName());
        sb.append(" ");
        boolean first = true;
        for (String user : userAddresses.keySet()) {
            if (!first) {
                sb.append("$$");
            }
            else {
                first = false;
            }
            sb.append(user);
            if (userAddresses.get(user)!=null) {
                sb.append(" ").append(userAddresses.get(user));
            }
        }
        return sb.toString();
    }

    @Override
    public void parseCommand() {
        userAddresses.clear();
        String tokensSubstr = getCommand().substring(8);
        String[] tokens = tokensSubstr.split("\\$\\$");
        if (tokens.length<=0) {
            return;
        }
        for (String token : tokens) {
            String[] userAddr = token.split(" ");
            if (userAddr.length>1) {
                userAddresses.put(userAddr[0], userAddr[1]);
            }
            else {
                userAddresses.put(userAddr[0], null);
            }
        }

    }


    public Map<String, String> getUserAddresses() {
        return userAddresses;
    }
}
